<template>
  <div class="study-records">
    <div class="page-header">
      <h2>学习记录</h2>
      <div class="header-actions">
        <el-select
          v-model="selectedUserId"
          placeholder="选择用户"
          clearable
          style="width: 200px; margin-right: 16px"
          @change="loadRecords"
        >
          <el-option
            v-for="user in users"
            :key="user.id"
            :label="user.username"
            :value="user.id"
          />
        </el-select>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="margin-right: 16px"
          @change="loadRecords"
        />
        <el-button :icon="Refresh" @click="loadRecords">刷新</el-button>
      </div>
    </div>

    <!-- 学习记录表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="id" label="记录ID" width="100" />
      <el-table-column prop="username" label="用户名" width="150" />
      <el-table-column prop="word" label="单词" width="150" />
      <el-table-column prop="isCorrect" label="答题结果" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isCorrect ? 'success' : 'danger'">
            {{ row.isCorrect ? '正确' : '错误' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="reviewCount" label="复习次数" width="100" />
      <el-table-column prop="studyTime" label="学习时间" min-width="180">
        <template #default="{ row }">
          {{ formatDate(row.studyTime) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getStudyRecordList } from '../api/studyRecord'
import { getUserList } from '../api/user'

// 数据
const tableData = ref([])
const users = ref([])
const loading = ref(false)
const selectedUserId = ref(null)
const dateRange = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

onMounted(() => {
  loadUsers()
  loadRecords()
})

// 加载用户列表
const loadUsers = async () => {
  try {
    const response = await getUserList({ page: 1, size: 1000 })
    if (response.code === 200) {
      users.value = response.data.list || []
    } else {
      ElMessage.error(response.message || '加载用户列表失败')
    }
  } catch (error) {
    console.error('加载用户列表失败：', error)
    ElMessage.error('加载用户列表失败')
  }
}

// 加载学习记录
const loadRecords = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    if (selectedUserId.value) {
      params.userId = selectedUserId.value
    }
    
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = formatDateForApi(dateRange.value[0])
      params.endDate = formatDateForApi(dateRange.value[1])
    }
    
    const response = await getStudyRecordList(params)
    if (response.code === 200) {
      tableData.value = response.data.list || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '加载学习记录失败')
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载学习记录失败：', error)
    ElMessage.error('加载学习记录失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分页
const handleSizeChange = (size) => {
  pageSize.value = size
  loadRecords()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadRecords()
}

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 格式化日期为API参数（YYYY-MM-DD HH:mm:ss）
const formatDateForApi = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
</script>

<style scoped>
.study-records {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 20px;
  color: #303133;
  margin: 0;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}
</style>

